<template>
  <el-container style="height: 100vh;">
    <el-header class="header">
      AI小说家
    </el-header>
    <el-main class="main">
      <div class="input-container">
        <el-input
          type="textarea"
          v-model="message"
          placeholder="在这里输入你的消息..."
          @keyup.enter="sendMessage"
          class="input-box">
        </el-input>
        <el-button type="primary" @click="sendMessage">发送</el-button>
      </div>
      <div class="chat-box">
        <div v-for="msg in messages" :key="msg.id" class="message">
          {{ msg.content }}
        </div>
      </div>
    </el-main>
  </el-container>
</template>

<script>
import axios from 'axios';
import { v4 as uuidv4 } from 'uuid';

export default {
  data() {
    return {
      message: '',
      messages: [],
      sessionId: uuidv4()
    };
  },
  methods: {
    sendMessage() {
      if (!this.message.trim()) {
        return;
      }
      const requestBody = {
        content: this.message,
        sessionId: this.sessionId
      };
      axios.post('/api/chat/send', requestBody)
        .then(response => {
          const responseData = response.data;
          if (responseData && responseData.data && responseData.code === 0) {
            this.messages.push({
              id: this.messages.length + 1,
              content: responseData.data.content
            });
            this.message = '';
          } else {
            console.error('接收到错误或格式无效:', responseData);
          }
        })
        .catch(error => {
          console.error('发送消息错误:', error);
          this.messages.push({
            id: this.messages.length + 1,
            content: `错误：${error.message || "与服务器通信失败"}`
          });
        });
    }
  }
}
</script>

<style scoped>
body {
  font-family: 'Microsoft YaHei', sans-serif; /* 微软雅黑字体 */
}

.header {
  background-color: rgba(46, 139, 87, 0.85); /* 深绿色背景，半透明 */
  color: white;
  text-align: center;
  padding: 10px;
  font-size: 24px;
  font-weight: bold;
}

.main {
  display: flex;
  flex-direction: column;
  justify-content: flex-start;
  padding: 20px;
  height: calc(100vh - 60px); /* 减去header的高度 */
}

.input-container {
  display: flex;
  align-items: center;
  margin-bottom: 20px; /* 输入框和按钮与消息列表之间的间距 */
}

.input-box {
  flex: 1;
  margin-right: 10px;
  min-height: 36px; /* 控制输入框高度 */
}

.chat-box {
  flex: 1;
  overflow-y: auto;
  background: rgba(255, 255, 255, 0.90); /* 半透明背景 */
  padding: 20px;
  border-radius: 10px;
}

.message {
  margin: 10px 0;
  font-size: 16px;
  color: #333;
  font-weight: bold; /* 字体加粗 */
}

.el-button {
  align-self: flex-end;
}
</style>
